package com.helper.excel;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.util.JxlsHelper;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;


/**
 * 使用这个工具类，请在 所在模块 build.gradle 加入下面的代码以便强制版本，否则会引入不支持自定义函数的新版本
 * compile ('org.jxls:jxls:2.4.3') {
 * force = true
 * }
 * 要了解如何创建模板，请阅读 https://www.cnblogs.com/klguang/p/6425422.html
 *
 * @description:
 * @author: cyj
 */
@Slf4j
public class JxlsExportExcelUtils {

    /**
     * Export excel *
     *
     * @param templateName template name
     * @param data         data
     * @throws IOException io exception
     */
    public static void exportExcel(OutputStream outputStreamm, String templateName, Object data) throws IOException {
        try (InputStream in = getInputStreamByTemplateName(templateName)) {
            Context context = new Context();
            JxlsHelper jxlsHelper = JxlsHelper.getInstance();
            Transformer transformer = jxlsHelper.createTransformer(in, outputStreamm);
            JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
            //evaluator.getJexlEngine().setFunctions(getCustomFunctions());
            Map<String, Object> map = (Map<String, Object>) JSON.toJSON(data);
            map.keySet().forEach(item -> context.putVar(item, map.get(item)));
            jxlsHelper.processTemplate(context, transformer);
            outputStreamm.flush();
        } catch (Exception e) {
            log.error("exportExcel 出错");
            log.error(e.getLocalizedMessage(), e.fillInStackTrace());
            throw e;
        }
    }

    private static InputStream getInputStreamByTemplateName(String templateName) throws IOException {
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        InputStream in = resourceLoader.getResource("classpath:/templates/" + templateName).getInputStream();
        return in;
    }


}